package cn.wolfcode.springboot_producer.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {


    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/hello")
    public String sendMsg(String message) throws Exception{
        SendResult sendResult = rocketMQTemplate.syncSend("01-boot:", message);
        System.out.println(sendResult.getMsgId());
        return "success";
    }
    @RequestMapping("/async")
    public void asyncSendMsg(String msg){
        rocketMQTemplate.asyncSend("01-boot", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult.getMsgId());
                System.out.println("消息发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("消息发送失败");
            }
        });
    }

    @RequestMapping("/oneWay")
    public String oneWay(String msg){
        rocketMQTemplate.sendOneWay("01-boot",msg);

        return "xxx";
    }

    @RequestMapping("/delay")
    public void delay(String msg){
        SendResult sendResult = rocketMQTemplate.syncSend("01-boot",
                MessageBuilder.withPayload(msg).build(), 3000, 3);
        System.out.println(sendResult.getMsgId());
    }

    @RequestMapping("/filter")
    public String filter(String msg,String tag){
        rocketMQTemplate.syncSend("01-boot:"+tag,msg);

        return "消息发送ok";
    }

    @RequestMapping("/defined")
    public String defined(String msg,String tag,String key){
        Map<String,Object> map = new HashMap<>();
        map.put("age",12);
        map.put("name","xx");
        map.put(MessageConst.PROPERTY_KEYS,key);
        rocketMQTemplate.convertAndSend("01-boot:"+tag,msg,map);
        return "消息发送 OK";
    }
}
